const App = {
    mixins: [Query],//配置文件，路径/utils/mixins.js
    data() {
        return {
            photo,
            page: {
                activeName: 'first',
                value1: '',
                value2:'',
                PageNumber: 1, //页码
                RowAmount: 10,
                Condition: window.btoa(unescape(encodeURIComponent("%%"))),
                ExtensionCondition: window.btoa(unescape(encodeURIComponent("AND village_project.Village_Number IN (" + getCookie('village') + ")"))),
            },
            form:{},
            showDialog1:false,
            project_examine_log_attachment:[],
            village_project_category:[],
            str1: '',
            str: '',
            data:[],
            Reason:'',
            fileUrl:'',
            showDialog1:false,
            Village_Project_Log_SerialNumber:''
        }
    },
    mounted() {
        $.ajax({
            headers: requestHeaders(),
            url: `${mh}/generalBusiness/generalQueryByTableName`,
            method: "post",
            data: {
                Data: 'village_project_category',
                Condition: `Row_Status='0'`,
            },
            success: (res) => {
                this.village_project_category = res;
            },
            complete: (XMLHttpRequest) => {
                requestPretreatment(XMLHttpRequest)
            },
        });
    },
    methods: {
        handleShow(row) {
            let { primary_key } = JSON.parse(
                document.getElementById("table").getAttribute("data-options")
            );
    
            if (row[primary_key]) {
                window.location.href ="./add.html?action=Modify&nodeKey=" + row[primary_key];
            }

        },
        check() {
            this.Treedata();
        },
        Treedata() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'village_project',
                    Condition: `Row_Status IN ('2','4','5') AND Project_Category_SerialNumber LIKE '%${this.page.value1}%' and Village_Number in (${getCookie('village')})`,
                },
                success: (data) => {
                    this.treeData = data; // 直接使用 this
                    if (data.length > 0) {
                        this.$nextTick(() => {
                            this.$refs.tree.setCurrentKey(data[0].Project_SerialNumber); // 选中 id=10 的节点
                        });
                        this.handleNodeClick(data[0]);
                    } else {
                        this.Tabletdata = []
                    }
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
                dataType: "json",
            });
        },
        preview(row) {
            this.fileUrl = photo + row.Attachment_URL;
            this.showDialog1 = true;
        },
        async download(row) {
            // if (row.Attachment_URL) {
            //     window.location.href = photo + row.Attachment_URL;
            // }
            let apiUrl = photo + row.Attachment_URL;
            let fileName = apiUrl.split('/').pop();
            try {
                const response = await fetch(apiUrl);
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = fileName || 'download';
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            } catch (error) {
                console.error('下载失败:', error);
            }
        },
        sumbit(i){                                this.showDialog = false;
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'village_project_log',
                    Condition: `Village_Project_Log_SerialNumber='${this.Village_Project_Log_SerialNumber}'`,
                },
                success: (data) => {
                    if (data.length == 1) {
                        data[0].Row_Status = i;
                        let lJSONObject_DataSet = {
                            Modify: {
                                village_project_log:data
                            },
                            Add: {}
                        }
                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '0',
                            Operation_Path: this.relativePath,
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]
                        submitSave(lJSONObject_DataSet, (res) => {
                            if (res.Status == 'success') {
                                this.Reason = '';
                                this.postgetList(this.page);
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                });
                            }
                            this.loading = false;
                        })
                    }
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        handlesh(row){
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                method: "post",
                data: {
                    Data: 'village_project_log_attachment',
                    Condition: `Village_Project_Log_SerialNumber='${row.Village_Project_Log_SerialNumber}'`,
                },
                success: (res) => {
                    this.data = res;
                    this.showDialog = true
                    this.Village_Project_Log_SerialNumber = row.Village_Project_Log_SerialNumber;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        
        handleClick() {
            if (this.page.activeName == 'first') {
                this.str1 = '';
            } else if (this.page.activeName == 'second') {
                this.str1 = "\r\nAND village_project_log.Row_Status = '0'\r\n";
            } else if (this.page.activeName == 'third') {
                this.str1 = "\r\nAND village_project_log.Row_Status = '2'\r\n";
            } else if (this.page.activeName == 'fourth') {
                this.str1 = "\r\nAND village_project_log.Row_Status = '3'\r\n";
            }
            this.page.ExtensionCondition = window.btoa(unescape(encodeURIComponent(this.str1 +"AND village_project.Village_Number IN (" + getCookie('village') + ")")));
            this.postgetList(this.page)
        },
        //树的点击筛选事件
        handleNodeClick(data, node) {
            this.page.value2 = data.Project_SerialNumber;
            this.page.Condition = window.btoa(unescape(encodeURIComponent("%" + data.Project_SerialNumber + "%")));
            this.postgetList(this.page);
        },
        examine(row) {
            let { primary_key } = JSON.parse(document.getElementById("table").getAttribute("data-options"));
            window.location.href = "./examine.html?action=Modify&nodeKey=" + row[primary_key];
        },
        getList() {
            const that = this;
            const { TableName } = JSON.parse(document.getElementById("table").getAttribute("data-options"));
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                method: "post",
                data: {
                    SQLSerialNumber: 's_base_sql_table_config',
                    Condition: window.btoa(unescape(encodeURIComponent("%" + this.relativePath + "%"))),
                    ExtensionCondition: '',
                },
                success: (data) => {
                    if (data.length > 0) {
                        that.columns = data;
                        that.checkedFields = data;
                        that.fields = data;
                        that.loading = true;
                        // that.postgetList(that.page);
                        
                    } 
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        examine1(row, is) {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'project',
                    Condition: `Project_SerialNumber='${row.Project_SerialNumber}'`,
                },
                success: (project) => {
                    if (is == '5') {
                        this.$confirm('此操作后该项目将会竣工,是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }).then(() => {
                            project[0].Project_Status = is;
                            let lJSONObject_DataSet = {
                                Modify: {
                                    project
                                },
                                Add: {
                                    project_examine_log: [{
                                        Project_SerialNumber: row.Project_SerialNumber,
                                        Row_Status: '3'
                                    }]
                                }
                            }
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: this.relativePath,
                                Operation_Main,
                                Operation_Interface: "generalSaveByRequestBody",
                                Operation_IP: getIpAddress()
                            }]
                            submitSave(lJSONObject_DataSet, (res) => {
                                if (res.Status == 'success') {
                                    this.postgetList(this.page)
                                }
                                this.loading = false;
                            })
                            // $.ajax({
                            //     headers: requestHeaders("JSON"),
                            //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                            //     method: "post",
                            //     data: JSON.stringify({
                            //         Data: lJSONObject_DataSet,
                            //     }),
                            //     success: (res) => {
                            //         if (res.Status == 'success') {
                            //             this.postgetList(this.page)
                            //         }
                            //     },
                            //     complete: (XMLHttpRequest) => {
                            //         this.loading = false;
                            //         requestPretreatment(XMLHttpRequest)
                            //     }
                            // });
                        }).catch(() => { });
                    } else if (is == '7') {
                        this.$prompt("请输入拒绝原因", '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                            inputPattern: /^\s*\S.+$/,
                            inputErrorMessage: "请输入拒绝原因"
                        }).then(({ value }) => {
                            project[0].Project_Status = is;
                            let lJSONObject_DataSet = {
                                Modify: {
                                    project
                                },
                                Add: {
                                    project_examine_log: [{
                                        Project_SerialNumber:  row.Project_SerialNumber,
                                        Reason: value,
                                        Row_Status: '4'
                                    }]
                                }
                            }
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: this.relativePath,
                                Operation_Main,
                                Operation_Interface: "generalSaveByRequestBody",
                                Operation_IP: getIpAddress()
                            }]
                            submitSave(lJSONObject_DataSet, (res) => {
                                if (res.Status == 'success') {
                                    this.postgetList(this.page)
                                }
                                this.loading = false;
                            })
                            // $.ajax({
                            //     headers: requestHeaders("JSON"),
                            //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                            //     method: "post",
                            //     data: JSON.stringify({
                            //         Data: lJSONObject_DataSet,
                            //     }),
                            //     success: (res) => {
                            //         if (res.Status == 'success') {
                            //             this.postgetList(this.page);
                            //         }
                            //     },
                            //     complete: (XMLHttpRequest) => {
                            //         this.loading = false;
                            //         requestPretreatment(XMLHttpRequest)
                            //     }
                            // });
                        }).catch(() => { });
                    }
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        success(row, res) {
            this.project_examine_log_attachment.push({
                uid: row.uid,
                Attachment_URL: res.fileName,
                Attachment_Name:row.name,
                Temp_Path:res.tempPath,
            })
        },
        remove(row) {
            if (!Object.keys(row).some(item => item.includes('_Original'))) {
                this.project_examine_log_attachment = this.project_examine_log_attachment.filter(i => i.uid != row.uid);
            } else {
                let obj = this.project_examine_log_attachment.filter(i => i.Attachment_SerialNumber == row.Attachment_SerialNumber)[0];
                obj.Row_Status = '1'
            }
        },
        handleRework(row){
            this.form = row;
            this.showDialog1 = true;
        },
        handleSubmit(row){
            this.loading = true;
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'project',
                    Condition: `Project_SerialNumber='${row.Project_SerialNumber}'`,
                },
                success: (project) => {
                    project[0].Project_Status = '6';
                    let lJSONObject_DataSet = {
                        Modify: {
                            project
                        },
                        Add: {
                            project_examine_log: [{
                                Project_SerialNumber:  row.Project_SerialNumber,
                                Row_Status: '5',
                                Children:{
                                    project_examine_log_attachment:this.project_examine_log_attachment
                                }
                            }]
                        }
                    }
                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '0',
                        Operation_Path: this.relativePath,
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]
                    submitSave(lJSONObject_DataSet, (res) => {
                        if (res.Status == 'success') {
                            this.showDialog1 = false;
                            this.postgetList(this.page);
                        }
                        this.loading = false;
                    })
                    // $.ajax({
                    //     headers: requestHeaders("JSON"),
                    //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                    //     method: "post",
                    //     data: JSON.stringify({
                    //         Data: lJSONObject_DataSet,
                    //     }),
                    //     success: (res) => {
                    //         if (res.Status == 'success') {
                    //             this.showDialog1 = false;
                    //             this.postgetList(this.page);
                    //         }
                    //         this.loading = false;
                    //     },
                    //     complete: (XMLHttpRequest) => {
                    //         requestPretreatment(XMLHttpRequest)
                    //     }
                    // });
                },
                complete: (XMLHttpRequest) => {
                    this.loading = false;
                    requestPretreatment(XMLHttpRequest)
                }
            })
        }
    },
};

const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-online-preview', ylOnlinePreview)
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
